<template>
  <div>
    <div v-if="tableJson.navigationTree.enable" style="float: left">
      <div style="margin-right: 15px">
        <el-input
            v-model="navigationTreeSearch"
            :placeholder="tableJson.navigationTree.fieldName"
            size="small"
            clearable
        />
        <el-scrollbar height="78vh">
          <el-tree
              ref="navigationTreeRef"
              :data="optionDatas[tableJson.navigationTree.optionId]?.options"
              :props="{
              children: 'children',
              label: 'label'
            }"
              :highlight-current="highlightNode"
              @node-click="navigationTreeNodeClick"
              :filter-node-method="navigationTreeFilterNode"
          />
        </el-scrollbar>
      </div>
    </div>
    <div v-if="isLoading" class="gridContainer" style="flex-grow: 1">
      <el-form :inline="true" size="small" :model="queryData.data" style="position: relative">
        <!-- 打开网格设置 -->
        <el-tooltip effect="dark" content="打开网格设置" placement="left">
          <div class="gridSet">
            <el-icon
                v-if="!setGrid && functionRole.includes('setGrid') && tableJson.setGrid"
                @click="openGridSet"
            ><Setting
            /></el-icon></div
          ></el-tooltip>
        <!-- 查询 -->
        <QueryView v-if="functionRole.includes('query')" v-model="queryData.data" :queryJson />

        <!--操作-->
        <div style="margin-bottom: 14px">
          <el-button
              v-if="functionRole.includes('add') && tableJson.data.add"
              @click="add({})"
              type="primary"
              size="small"
          >添加</el-button
          >

          <el-button
              v-if="functionRole.includes('import') && tableJson.data.import"
              @click="importExcel"
              type="primary"
              size="small"
          >导入</el-button
          >

          <el-button
              v-if="functionRole.includes('export') && tableJson.data.export"
              @click="exportExcel"
              type="primary"
              size="small"
          >导出</el-button
          >

          <el-popconfirm
              v-if="functionRole.includes('batchDel') && tableJson.data.batchDel"
              :title="'你确定要删除选中的 ' + batchData.length + ' 条数据吗?'"
              @confirm="del(scope.row.id)"
          >
            <template #reference
            ><el-button size="small" type="danger">批量删除</el-button></template
            >
          </el-popconfirm>
          <!-- 查询列表扩展插槽 -->
          <slot name="query"> </slot>

          <span style="float: right">
            <el-button @click="search" type="primary" size="small">搜索</el-button>
            <el-button @click="refresh" icon="Refresh" size="small" type="primary" />
          </span>
        </div>
      </el-form>
      <!-- 标签模式 -->
      <span v-if="tableJson.tagModel.enable"
      ><el-checkbox-group
          v-if="tableJson.tagModel.multiple"
          v-model="tagValues"
          @change="tagModelChange"
          size="small"
      >
          <el-checkbox-button :label="tableJson.tagModel.fieldName" value disabled />
          <el-checkbox-button
              v-for="(item, index) in optionDatas[tableJson.tagModel.optionId]?.options"
              :key="index"
              :value="item.value"
              :label="item.label"
          />
        </el-checkbox-group>
        <el-radio-group v-else v-model="tagValues" @change="tagModelChange" size="small">
          <el-radio-button :label="tableJson.tagModel.fieldName" disabled />
          <el-radio-button
              v-for="(item, index) in optionDatas[tableJson.tagModel.optionId]?.options"
              :key="index"
              :value="item.value"
              :label="item.label"
          /> </el-radio-group
        ></span>

      <!-- 表格 -->
      <el-table
          class="gridTable"
          ref="tableRef"
          :data="tableData"
          :border="tableJson.border"
          :stripe="tableJson.stripe"
          style="width: 100%"
          row-key="id"
      >
        <el-table-column v-if="tableJson.data.batch" type="selection" align="center" width="55" />
        <el-table-column
            v-if="tableJson.index"
            :align="tableJson.align"
            type="index"
            label="序号"
            width="60"
            fixed
        />
        <template v-for="(item, index) in fieldJson" :key="index">
          <el-table-column
              v-if="item.isShow"
              :label="item.label"
              :prop="item.field"
              :min-width="item.minWidth"
              :width="item.width"
              :sortable="item.isSort"
              v-bind="item.fixed === 'false' ? {} : { fixed: item.fixed }"
              :align="item.align || tableJson.align"
              :header-align="item.headerAlign || tableJson.headerAlign"
              #default="scope"
          >
            <span v-if="$slots[item.field]">
              <!-- 数据处理扩展插槽 -->
              <slot :name="item.field" :scope="scope" :field="item"></slot>
            </span>
            <span
                v-else
                @click="item.isCopy ? copyText($event) : null"
                :class="{ cursor: item.isCopy }"
            >
              <el-switch v-if="item.type.value === 'switch'" v-model="scope.row[item.field]" />
              <span v-else-if="item.type.value === 'image'" class="demo-image__preview">
                <el-image
                    :src="scope.row[item.field]"
                    :preview-src-list="previewSrcList"
                    preview-teleported
                    :initial-index="handleRowClick(scope.row[item.field])"
                    :style="{
                    height: item.type.image.height ? item.type.image.height + 'px' : '50px'
                  }"
                    fit="contain"
                />
              </span>
              <el-link
                  v-else-if="item.type.value === 'url'"
                  type="default"
                  :href="scope.row[item.field]"
                  target="_blank"
                  style="color: #296dff"
              >{{ GridFieldShowHandle.url(item, scope.row) }}</el-link
              >
              <el-button
                  v-else-if="item.type.value === 'editor'"
                  @click="editorPreView(scope.row[item.field])"
                  type="primary"
                  size="small"
              >打开编辑器</el-button
              >
              <el-button
                  v-else-if="item.type.value === 'json'"
                  @click="jsonPreView(scope.row[item.field])"
                  type="primary"
                  size="small"
              >打开Json</el-button
              >
              <el-button
                  v-else-if="item.type.value === 'JavaScript'"
                  @click="javaScriptPreView(scope.row[item.field])"
                  type="primary"
                  size="small"
              >打开JavaScript</el-button
              >
              <!--选项-->
              <template v-else-if="item.type.value === 'select'">
                <template v-if="optionDatas[item.type.select.optionId]">
                  <!-- 树形选项 -->
                  <el-tree-select
                      v-if="item.type.select.tree && !item.type.select.showText"
                      v-model="scope.row[item.field]"
                      :data="optionDatas[item.type.select.optionId].options"
                      :multiple="item.type.select.multiple"
                      :render-after-expand="false"
                      show-checkbox
                  />
                  <el-select
                      v-else-if="!item.type.select.tree && !item.type.select.showText"
                      v-model="scope.row[item.field]"
                      placeholder="Select"
                      size="small"
                      style="width: 160px"
                  >
                    <el-option
                        v-for="(item, index) in optionDatas[item.type.select.optionId].options"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>

                  <!--选项-文本-->
                  <span v-else-if="!item.type.select.tree && item.type.select.showText">
                    <span v-if="optionDatas[item.type.select.optionId]">
                      <!-- 标签显示 -->
                      <el-tag
                          v-if="item.type.select.showTag"
                          :type="GridFieldShowHandle.selectTag(item, scope.row, optionDatas)"
                      >{{ GridFieldShowHandle.selectText(item, scope.row, optionDatas) }}</el-tag
                      >
                      <span v-else>{{
                          GridFieldShowHandle.selectText(item, scope.row, optionDatas)
                        }}</span>
                    </span>
                  </span>

                  <!--树状选项-文本-->
                  <span v-else-if="item.type.select.tree && item.type.select.showText"> 暂未 </span>
                </template>
              </template>
              <el-input
                  v-else-if="item.type.value === 'password'"
                  class="no_border"
                  v-model="scope.row[item.field]"
                  type="password"
                  show-password
              />

              <span v-else v-html="GridFieldShowHandle.text(item, scope.row)"> </span>
            </span>
          </el-table-column>
        </template>
        <!-- 操作列 -->
        <el-table-column
            ref="operationRef"
            v-if="isShowOperation"
            :align="tableJson.operations.align"
            :min-width="tableJson.operations.minWidth"
            :width="tableJson.operations.width"
            label="操作"
            fixed="right"
            class-name="operation"
        >
          <template #default="scope">
            <template v-for="(item, index) in tableJson.operations.base" :key="index">
              <MoveView
                  v-if="item.type === 'move' && operationsShow.move"
                  :style="{ order: item.order }"
                  :row="scope.row"
                  :requestApi="editApi"
                  @moveOk="loadData"
              />
              <el-button
                  v-if="item.type === 'addChild' && operationsShow.addChild"
                  @click="add({ pid: scope.row.id })"
                  :style="{ order: item.order }"
                  size="small"
                  type="primary"
              >{{ item.name }}</el-button
              >
              <el-button
                  v-if="item.type === 'edit' && operationsShow.edit"
                  :style="{ order: item.order }"
                  size="small"
                  @click="edit(scope.row)"
              >{{ item.name }}</el-button
              >
              <!-- <el-popconfirm
                v-if="item.type === 'del' && operationsShow.del"
                title="你确定要删除这条数据吗?"
                :style="{ order: item.order }"
                @confirm="del(scope.row.id)"
              >
                <template #reference>
                  <el-button size="small" type="danger">{{ item.name }}</el-button>
                </template>
              </el-popconfirm> -->
              <el-button
                  v-if="item.type === 'del' && operationsShow.del"
                  :style="{ order: item.order }"
                  @click="confirmDelOpen(scope.row.id)"
                  size="small"
                  type="danger"
              >{{ item.name }}</el-button
              >
              <el-button
                  v-if="item.type === 'copy' && operationsShow.copy"
                  :style="{ order: item.order }"
                  size="small"
                  type="primary"
                  @click="copy(scope.row.id)"
              >{{ item.name }}</el-button
              >
            </template>
            <!-- 扩展功能 -->
            <template v-for="(expandItem, index) in tableJson.operations.expand" :key="index"
            ><el-button
                v-if="expandItem.enable"
                :style="{ order: expandItem.order }"
                type="primary"
                size="small"
                @click="expand(expandItem, scope.row)"
            >{{ expandItem.name }}</el-button
            >
            </template>
            <!-- 操作扩展插槽 -->
            <slot name="operate" :scope="scope"></slot>
          </template>
        </el-table-column>
      </el-table>

      <!-- 确认删除弹框 -->
      <el-dialog
          v-if="operationsShow.del"
          v-model="confirmDelDialogVisible"
          title="确认删除"
          width="500"
      >
        <span>你确定要删除这条数据吗</span>
        <template #footer>
          <div>
            <el-button @click="confirmDelDialogVisible = false">Cancel</el-button>
            <el-button type="primary" @click="confirmDel()"> Confirm </el-button>
          </div>
        </template>
      </el-dialog>
      <el-pagination
          v-if="!tableJson.tree.value"
          size="small"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          v-model:current-page="queryData.page.pageNum"
          v-model:page-size="queryData.page.pageSize"
          :total="dataObj.total"
          class="mt-4 pagination"
          @change="pageChange"
      />
      <EditView
          v-if="editSetting.isOpen"
          :modal="editSetting.data"
          :editDisables="props.editDisables"
          :editJson="props.gridJson.editJson"
          :requestApi="editApi"
          @close="
          () => {
            editSetting.isOpen = false
            isOpenAdd = false
          }
        "
          @editOk="search"
      >
        <!-- 编辑字段扩展插槽 -->
        <template #EDIT_ADD_FIELD>
          <slot name="EDIT_ADD_FIELD" :modal="editSetting.data"></slot>
        </template>
      </EditView>
      <AddView
          v-if="addSetting.isOpen"
          :modal="addSetting.data"
          :editDisables="props.editDisables"
          :addJson="props.gridJson.addJson"
          :requestApi="editApi"
          @close="
          () => {
            addSetting.isOpen = false
            isOpenAdd = false
          }
        "
          @editOk="search"
      >
        <!-- 添加字段扩展插槽 -->
        <template #ADD_ADD_FIELD="{ modal }">
          <slot name="ADD_ADD_FIELD" :modal="modal"></slot>
        </template>
      </AddView>
      <ImportView
          v-if="importViewOpen"
          :importJson="props.gridJson.importJson"
          :requestApi="requestApi"
          :gridId="props.gridJson.id"
          @close="
          () => {
            importViewOpen = false
            isOpenAdd = false
          }
        "
          @editOk="search"
      />
      <EditorPreView
          v-if="editorPreSetting.isOpen"
          v-model="editorPreSetting.isOpen"
          :data="editorPreSetting.data"
          @editOk="editorPreSetting.isOpen = false"
      />
      <JsonPreView
          v-if="jsonPreSetting.isOpen"
          v-model="jsonPreSetting.isOpen"
          :data="jsonPreSetting.data"
          @editOk="jsonPreSetting.isOpen = false"
      />
      <MonacoEditPreView
          v-if="javaScriptPreSetting.isOpen"
          v-model="javaScriptPreSetting.isOpen"
          :data="javaScriptPreSetting.data"
          @editOk="javaScriptPreSetting.isOpen = false"
      />
      <GridPreView
          v-if="expandSetting.isOpen"
          :expandItem="expandSetting.expandItem"
          :row="expandSetting.row"
          @editOk="expandSetting.isOpen = false"
      />
    </div>
  </div>
</template>
<script setup>
import GridFieldShowHandle from '@/utils/GridFieldShowHandle.js'
import QueryView from './QueryView.vue'
import EditView from './EditView.vue'
import AddView from './AddView.vue'
import ImportView from './ImportView.vue'
import { ref, inject, computed, watch, reactive, onBeforeMount } from 'vue'
import { ElMessage } from 'element-plus'
import EditorPreView from '@/views/template/util/EditorPreView.vue'
import JsonPreView from '@/views/template/util/JsonPreView.vue'
import MonacoEditPreView from '@/views/template/util/MonacoEditPreView.vue'
import MoveView from './MoveView.vue'
import GridPreView from '@/views/template/util/GridPreView.vue'
import { usePageTabStore } from '@/stores/pageTab'
import { useOptionDataStore } from '@/stores/optionData'
import { storeToRefs } from 'pinia'
import { useRoute } from 'vue-router'
const pageTabStore = usePageTabStore()
let props = defineProps(['setGrid', 'gridJson', 'mode', 'isPreview', 'editDisables'])
if (props.setGrid) {
  console.log('----------网格设置模式----------')
}
defineExpose({
  search,
  refresh,
  tableRef: () => tableRef.value
})
const route = useRoute()
// 权限
const functionRole = ref()
const { optionDatas } = storeToRefs(useOptionDataStore())
// 查询数据
let queryData = defineModel('queryData')
// 标签模式筛选值
let tagValues = ref()
// 默认值
if (!queryData.value) {
  queryData.value = reactive({ data: { extend: {} }, page: { pageNum: 1, pageSize: 20 } })
}
// 保存原始查询条件
const queryDataOld = JSON.parse(JSON.stringify(queryData.value))
// 编辑数据
let editData = defineModel('editData')
// 默认值
if (!editData.value) {
  editData.value = reactive({})
}
// 保存原始编辑条件
const editDataOld = JSON.parse(JSON.stringify(editData.value))
// 初始化状态
const initStatus = ref({
  jsonEdit: false,
  queryJsonEdit: false,
  roleLoad: false
})
const isLoading = computed(() => {
  return initStatus.value.jsonEdit && initStatus.value.queryJsonEdit && initStatus.value.roleLoad
})
// 网格设置统一获取
const api = inject('api')
// 获取网格api
const requestApi = api.getApi(props.gridJson.api, props.gridJson.id)
const editApi = api.getApi(props.gridJson.editApi, props.gridJson.id)
// 表格字段属性
const fieldJson = props.gridJson.fieldJson
// 表格属性
const tableJson = props.gridJson.tableJson
// 查询配置
const queryJson = props.gridJson.queryJson
const previewSrcList = ref([])
// 导入页面开关
const importViewOpen = ref(false)
// 添加配置
const addSetting = reactive({ isOpen: false, data: '添加数据' })
// 编辑配置
const editSetting = reactive({ isOpen: false, data: '编辑数据' })
// 预览富文本配置
const editorPreSetting = reactive({ isOpen: false, data: '富文本' })
// 预览json配置
const jsonPreSetting = reactive({ isOpen: false, data: 'json预览' })
// 预览javaScript配置
const javaScriptPreSetting = reactive({ isOpen: false, data: 'javaScript' })
// 预览扩展功能配置
const expandSetting = reactive({ isOpen: false, expandItem: '扩展配置', row: '行数据' })
// 操作栏ref
const operationRef = ref(null)
// 导航树筛选
const navigationTreeRef = ref()
// 搜素条件
const navigationTreeSearch = ref('')
// 重置
const valueArr = ref([])
// 当前选中节点
const oldNode = ref()
// 高亮
const highlightNode = ref(false)
watch(navigationTreeSearch, (val) => {
  navigationTreeRef.value.filter(val)
})
function navigationTreeFilterNode(value, data) {
  // 对树节点进行筛选时执行的方法， 返回 false 则表示这个节点会被隐藏
  if (!value) return true
  return data.label.includes(value)
}
// 树形模式下选择节点
function navigationTreeNodeClick(values) {
  // 判断是否重复点击取消筛选
  if (oldNode.value === values) {
    // 取消选中高亮
    highlightNode.value = false
    // 重置
    queryData.value.data.extend[tableJson.navigationTree.field] = []
    oldNode.value = null
    valueArr.value = []
    search()
  } else {
    // 选中高亮
    highlightNode.value = true
    // 记录当前点击节点
    oldNode.value = values
    // 重置
    valueArr.value = []
    // 递归获取值
    navigationTreeValuesChange(values)
    // 插入查询字段
    queryData.value.data.extend[tableJson.navigationTree.field] = valueArr.value
    search()
  }
}
//导航树选择节点-树形节点值转数组-数递归获取值
function navigationTreeValuesChange(values) {
  if (values.children.length) {
    for (const item of values.children) {
      if (item.children.length) {
        navigationTreeValuesChange(item)
      } else {
        valueArr.value.push(item.value)
      }
    }
  } else {
    valueArr.value.push(values.value)
  }
}
// 查询强制添加导航树条件
function addNavigationTreeQueryData() {
  if (tableJson.navigationTree.enable && valueArr.value.length > 0) {
    queryData.value.data.extend[tableJson.navigationTree.field] = valueArr.value
  }
}
// 操作按钮显示控制
const operationsShow = computed(() => {
  let baseShowObj = {}
  for (const item of tableJson.operations.base) {
    if (item.enable && functionRole.value.includes(item.type)) {
      // 移动和添加子项只有树形网格才有
      if (item.type === 'move' || item.type === 'addChild') {
        if (tableJson.tree.value) {
          baseShowObj[item.type] = true
        } else {
          baseShowObj[item.type] = false
        }
      } else {
        baseShowObj[item.type] = true
      }
    } else {
      baseShowObj[item.type] = false
    }
  }
  console.log('基础按钮显示', baseShowObj)
  return baseShowObj
})
// 判断是否有显示基础操作按钮
function ifBaseOperationShow() {
  for (const key in operationsShow.value) {
    if (operationsShow.value[key]) {
      console.log('判断是否有显示基础操作按钮', true)
      return true
    }
  }
  console.log('判断是否有显示基础操作按钮', false)
  return false
}
// 是否有显示的扩展功能按钮
function ifExpandShow() {
  for (const item of tableJson.operations.expand) {
    if (item.enable) return true
  }
  return false
}
// 操作栏是否显示
const isShowOperation = computed(() => {
  const isShow =
      tableJson.operations.isShow &&
      (ifExpandShow() || ifBaseOperationShow() || operationRef.value?.$slots.default?.length > 0)
  console.log('操作栏是否显示', isShow)
  return isShow
})
// 删除确认框显示
const confirmDelDialogVisible = ref(false)
// 待确认删除id
const confirmDelId = ref()
// 打开确认删除框
function confirmDelOpen(id) {
  confirmDelDialogVisible.value = true
  confirmDelId.value = id
}
// 确认删除
function confirmDel() {
  confirmDelDialogVisible.value = false
  del(confirmDelId.value)
}
// 将网格设置页z-index置高,打开编辑或添加页面需设置为true
const isOpenAdd = inject('isOpenAdd', ref(false))
const dataObj = ref({ total: 0 })
const tableData = ref([])
const tableRef = ref()
const batchData = ref([])
watch(
    () => tableRef.value?.getSelectionRows(),
    () => {
      batchData.value = tableRef.value ? tableRef.value.getSelectionRows() : []
    },
    { deep: true }
)

onBeforeMount(() => {
  console.log('正常页面使用')
  loadData()
  // 正常页面使用
  jsonEdit()
  queryJsonEdit()
  roleLoad()
  // 重置查询条件
  // queryData.value.data = { extend: {} }
})

// 加载权限
function roleLoad() {
  // 预览模式加载所有权限
  if (props.setGrid) {
    // 获取权限模版列表
    functionRole.value = JSON.parse(sessionStorage.getItem('functionRole'))
  } else {
    functionRole.value = JSON.parse(JSON.stringify(route.meta.functionRole))
  }
  initStatus.value.roleLoad = true
}

function queryJsonEdit() {
  for (const key in queryJson) {
    const item = queryJson[key]
    // 获取最新选项数据
    if (item.type.value === 'select' && item.type.select.optionId) {
      useOptionDataStore().add(item.type.select.optionId)
    }
  }
  initStatus.value.queryJsonEdit = true
}

function jsonEdit() {
  // 初始化数据
  // 判断是否首次
  // if (tableData.value.length === 0) {
  //   loadData()
  // }
  const imageFileds = []
  previewSrcList.value = []
  for (const key in fieldJson) {
    const item = fieldJson[key]
    // 字段预处理
    // 获取最新选项数据
    if (item.type.value.indexOf('select') !== -1 && item.type.select.optionId) {
      useOptionDataStore().add(item.type.select.optionId)
    }
    // 图片预览处理
    if (item.type.value === 'image') {
      imageFileds.push(item)
      tableData.value.forEach((item2) => {
        previewSrcList.value.push(item2[item.field])
      })
    }
  }
  initStatus.value.jsonEdit = true
}

// // 点击复制
// function copyText(event) {
//   const copyContent = event.target.innerText.trim()
//   if (copyContent) {
//     if (!navigator.clipboard) {
//       ElMessage.warning('当前浏览器不支持剪贴板功能[1.非本地运行 2.非https环境 3.禁止复制权限]')
//       return
//     }
//     navigator.clipboard.writeText(copyContent).then(
//       () => {
//         ElMessage({
//           message: '复制成功：' + copyContent,
//           type: 'success'
//         })
//         // 复制成功的逻辑
//       },
//       (error) => {
//         ElMessage.error('复制失败', error)
//         // 复制失败的逻辑
//       }
//     )
//   }
// }

function copyText(event) {
  const codeToCopy = event.target.innerText.trim()
  if (navigator.clipboard && window.isSecureContext) {
    // 安全域使用现代API
    navigator.clipboard
        .writeText(codeToCopy)
        .then(() => successHandler(codeToCopy))
        .catch((err) => errorHandler(err))
  } else {
    // 非安全域降级方案
    const textArea = document.createElement('textarea')
    textArea.value = codeToCopy
    textArea.style.position = 'absolute'
    textArea.style.opacity = 0
    document.body.appendChild(textArea)
    textArea.select()

    try {
      document.execCommand('copy')
      successHandler(codeToCopy)
    } catch (err) {
      errorHandler(err)
    } finally {
      textArea.remove()
    }
  }
}

// 统一处理成功/失败提示
const successHandler = (codeToCopy) => {
  ElMessage({
    message: '复制成功：\n' + codeToCopy,
    type: 'success'
  })
}
const errorHandler = (err) => console.error('复制失败:', err)
// 获取当前行索引
function handleRowClick(url) {
  return previewSrcList.value.indexOf(url)
}

// 查询前参数处理
function queryBefore() {
  const queryDataTemp = { ...queryData.value.data }
  for (const key in queryJson) {
    const item = queryJson[key]
    let queryValue = queryData.value.data[item.field]
    if (item.type.value === 'select' && item.type.select.multiple) {
      queryValue = queryData.value.data.extend[item.field]
      // 若多选选项清除选项，则需删除该查询字段，否则后端无法排除该字段，导致报错
      if (queryValue?.length === 0) {
        delete queryDataTemp.extend[item.field]
      }
    }
  }
  return queryDataTemp
}
// 标签模式下选择标签
function tagModelChange(values) {
  if (values?.length > 0) {
    queryData.value.data.extend[tableJson.tagModel.field] = values
  } else {
    delete queryData.value.data.extend[tableJson.tagModel.field]
  }
  search()
}

function search() {
  const queryDataOldObj = JSON.parse(JSON.stringify(queryDataOld.data))
  const extentTemp = queryData.value.data.extend
  queryData.value.data = {
    ...queryData.value.data,
    ...queryDataOldObj
  }
  // 防止上面操作extend被queryDataOld.data内的extend：{}覆盖
  queryData.value.data.extend = {
    ...extentTemp,
    ...queryDataOldObj.extend
  }
  // 查询前参数处理
  const queryDataTemp = queryBefore()
  loadData(queryDataTemp)
}

// 强制添加标签条件
function addTagQueryData() {
  if (tagValues.value?.length > 0) {
    queryData.value.data.extend[tableJson.tagModel.field] = tagValues.value
  }
}

function refresh() {
  queryData.value.data = JSON.parse(JSON.stringify(queryDataOld.data))
  loadData()
}

function pageChange() {
  loadData()
}
function add(data) {
  // 打开添加页面
  addSetting.isOpen = true
  isOpenAdd.value = true
  addSetting.data = { ...data, ...editDataOld }
}

function edit(row) {
  // 打开编辑界面
  editSetting.isOpen = true
  isOpenAdd.value = true
  editSetting.data = { ...row }
}

function importExcel() {
  // 打开添加页面
  importViewOpen.value = true
  isOpenAdd.value = true
}

function expand(expandItem, row) {
  // 打开扩展功能页面
  expandSetting.isOpen = true
  expandSetting.expandItem = expandItem
  expandSetting.row = row
}

// 复制
function copy(id) {
  editApi.copy(id).then((data) => {
    search()
  })
}

// 导出
function exportExcel() {
  requestApi.exportExcel({ data: queryData.value.data, gridId: props.gridJson.id })
}

// 查询数据
function loadData(queryDataVlaue) {
  // 标签条件强制添加
  addTagQueryData()
  // 导航树条件强制添加
  addNavigationTreeQueryData()
  if (!queryDataVlaue) {
    queryDataVlaue = queryData.value.data
  }
  if (tableJson.tree.value) {
    requestApi.tree(queryDataVlaue).then((data) => {
      dataObj.value = data.data
      tableData.value = data.data
      queryAfter()
    })
  } else {
    requestApi.page({ data: queryDataVlaue, page: queryData.value.page }).then((data) => {
      dataObj.value = data.data
      tableData.value = data.data.records
      queryAfter()
    })
  }
}

// 查询后处理
function queryAfter() {
  jsonEdit()
}

function del(id) {
  editApi.del(id).then(
      () => {
        ElMessage({
          message: '删除成功',
          type: 'success'
        })
        // 复制成功的逻辑
        search()
      },
      (error) => {
        ElMessage.error('删除失败', error)
        // 复制失败的逻辑
      }
  )
}

// 打开富文本预览
function editorPreView(data) {
  editorPreSetting.isOpen = true
  editorPreSetting.data = data
}
// 打开json预览
function jsonPreView(data) {
  jsonPreSetting.isOpen = true
  jsonPreSetting.data = JSON.parse(data)
}
// 打开代码预览
function javaScriptPreView(data) {
  javaScriptPreSetting.isOpen = true
  javaScriptPreSetting.data = data
}

function openGridSet() {
  pageTabStore.add('网格设置-' + props.gridJson.name, '/home/grid/' + props.gridJson.id)
}
</script>
<style scoped>
.gridContainer {
  display: flex;
  flex-direction: column; /* 垂直排列 */
  height: 80vh; /* 父容器占满视口 */
}
.gridTable {
  flex: 1; /* 占满剩余空间 */
  overflow: auto; /* 内容溢出时滚动 */
}
.cursor:hover {
  cursor: pointer;
}
/* .el-form {
  margin: 0px 10px;
} */
.pagination {
  /* margin-top: 14px; */
}
/* 去除输入框边框 */
:deep(.no_border .el-input__wrapper) {
  align-items: center;
  /* background-color: rgba(255, 255, 255, 1) !important; */
  box-shadow: none;
}

.gridSet {
  position: absolute; /* 使按钮保持固定位置 */
  top: -5px;
  right: -5px;
  font-size: 20px;
  cursor: pointer;
}
/* 操作列行内排序规则 */
:deep(.operation > .cell) {
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}
/* 禁用button自动间隔，使用flex间隔和排序 */
:deep(.operation > .cell > button) {
  margin-left: 0;
}
</style>
